/**
 * @param {number} numCourses
 * @param {number[][]} prerequisites
 * @return {number[]}
*/
var findOrder = function(numCourses, prerequisites) {
  if(numCourses == 1)
    return [0];
  function clearIndex(index) {
    for(let i = 0; i < numCourses; i++) {
      if(arr[i] && arr[i].indexOf(index) != -1) {
        let deleteIndex = arr[i].indexOf(index);
        arr[i].splice(deleteIndex, 1);
      }
    }

  }
  let arr = [], result = [];
  for(let i = 0; i < numCourses; i++) {
    arr.push([]);
  }
  for(let i = 0; i < prerequisites.length; i++) {
    arr[prerequisites[i][0]].push(prerequisites[i][1]);
  }
  for(let i = 0; i < numCourses; i++) {
    for(let j = 0; i < numCourses; j++) {
      if(arr[j] && arr[j].length == 0) {
        result.push(j);
        clearIndex(j);
        arr[j] = undefined;
        break;
      }
      if(j == numCourses - 1) {
        return [];
      }
    }
  }
  return result;
};
let numCourses = 2, prerequisites = [[1,0]];
console.log(findOrder(numCourses, prerequisites));
numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]];
console.log(findOrder(numCourses, prerequisites));
numCourses = 1, prerequisites = [];
console.log(findOrder(numCourses, prerequisites));

